import { defineStore } from 'pinia'
import { ref } from 'vue'
import api from '@/services/api'

export const useUserStore = defineStore('user', () => {
    // 登录状态
    const isLoggedIn = ref(false)

    // 用户基础信息
    const userInfo = ref({
        userId: null,
        username: '',
        email: '',
        phone: '',
        nickname: '',
        avatarUrl: '',
        gender: null,
        birthday: null,
        introduction: '',
        hobby: ''
    })

    // 用户等级信息
    const levelInfo = ref({
        currentLevel: 0,
        currentExp: 0,
        requiredExp: 0,
        levelName: ''
    })

    // 会员信息
    const membershipInfo = ref(null)

    // 统计信息
    const statisticsInfo = ref({
        followerCount: 0,
        followingCount: 0,
        collectionCount: 0
    })

    // Token
    const token = ref('')

    // 初始化用户状态（从本地存储加载）
    const initUserState = () => {
        const storedToken = localStorage.getItem('auth_token')
        if (storedToken) {
            token.value = storedToken
            isLoggedIn.value = true
            // 尝试从 localStorage 获取用户基本信息
            const storedUserInfo = localStorage.getItem('user_info')
            if (storedUserInfo) {
                try {
                    const parsedUserInfo = JSON.parse(storedUserInfo)
                    if (parsedUserInfo.userId) {
                        userInfo.value.userId = parsedUserInfo.userId
                    }
                } catch (e) {
                    console.warn('解析存储的用户信息失败:', e)
                }
            }
        }
    }

    // 登录方法
    const login = (loginData) => {
        console.log('登录数据:', loginData)
        token.value = loginData.token
        isLoggedIn.value = true
        localStorage.setItem('auth_token', loginData.token)
        
        // 保存用户基本信息到 localStorage 和 store
        if (loginData.userInfo && loginData.userInfo.userId) {
            userInfo.value.userId = loginData.userInfo.userId
            // 将用户信息保存到 localStorage
            localStorage.setItem('user_info', JSON.stringify(loginData.userInfo))
        }
        
        // 登录后立即获取用户详情
        fetchUserDetail()
    }

    const fetchUserDetail = async () => {
        try {
            // 改进用户ID获取逻辑
            let userId = getUserId()
            
            if (!userId) {
                console.warn('用户ID不存在，无法获取详情')
                throw new Error('用户ID不存在，请重新登录')
            }
            
            console.log('正在获取用户详情，userId:', userId)
            const response = await api.userApi.getUserDetail(userId)
            console.log('获取用户详情响应:', response)
            
            if (response.code === 200) {
                updateUserData(response.data)
            } else {
                throw new Error(response.message || '获取用户详情失败')
            }
        } catch (error) {
            console.error('获取用户详情失败:', error)
            throw error
        }
    }

    // 新增：统一的用户ID获取方法
    const getUserId = () => {
        // 1. 先从当前 store 中获取
        if (userInfo.value.userId) {
            return userInfo.value.userId
        }
        
        // 2. 从 localStorage 获取
        try {
            const storedUserInfo = localStorage.getItem('user_info')
            if (storedUserInfo) {
                const parsedUserInfo = JSON.parse(storedUserInfo)
                if (parsedUserInfo.userId) {
                    // 同步到 store
                    userInfo.value.userId = parsedUserInfo.userId
                    return parsedUserInfo.userId
                }
            }
        } catch (e) {
            console.warn('从 localStorage 解析用户信息失败:', e)
        }
        
        // 3. 尝试从 token 中解析（如果后端 token 包含用户ID）
        try {
            const storedToken = token.value || localStorage.getItem('auth_token')
            if (storedToken) {
                // 这里可以添加 JWT token 解析逻辑
                // const payload = parseJWT(storedToken)
                // if (payload && payload.userId) {
                //     userInfo.value.userId = payload.userId
                //     return payload.userId
                // }
            }
        } catch (e) {
            console.warn('从 token 解析用户ID失败:', e)
        }
        
        return null
    }

    // 更新用户数据
    const updateUserData = (userDetail) => {
        userInfo.value = {
            userId: userDetail.userId,
            username: userDetail.username,
            email: userDetail.email,
            phone: userDetail.phone,
            nickname: userDetail.nickname,
            avatarUrl: userDetail.avatarUrl,
            gender: userDetail.gender,
            birthday: userDetail.birthday,
            introduction: userDetail.introduction,
            hobby: userDetail.hobby
        }

        levelInfo.value = {
            currentLevel: userDetail.levelInfo?.currentLevel || 0,
            currentExp: userDetail.levelInfo?.currentExp || 0,
            requiredExp: userDetail.levelInfo?.requiredExp || 0,
            levelName: userDetail.levelInfo?.levelName || ''
        }

        membershipInfo.value = userDetail.membershipInfo

        statisticsInfo.value = {
            followerCount: userDetail.statisticsInfo?.followerCount || 0,
            followingCount: userDetail.statisticsInfo?.followingCount || 0,
            collectionCount: userDetail.statisticsInfo?.collectionCount || 0
        }
    }

    // 修复方法名：updateUserProfile -> updateUserInfo
    const updateUserInfo = async (userId, updateData) => {
        try {
            const response = await api.userApi.updateUser(userId, updateData)
            if (response.code === 200) {
                // 更新成功后重新获取用户详情
                await fetchUserDetail()
                return response
            }
            return response
        } catch (error) {
            console.error('更新用户信息失败:', error)
            throw error
        }
    }

    // 登出方法
    const logout = () => {
        isLoggedIn.value = false
        token.value = ''
        resetUserData()
        localStorage.removeItem('auth_token')
        localStorage.removeItem('user_info') // 清除用户信息
    }

    // 重置用户数据
    const resetUserData = () => {
        userInfo.value = {
            userId: null,
            username: '',
            email: '',
            phone: '',
            nickname: '',
            avatarUrl: '',
            gender: null,
            birthday: null,
            introduction: '',
            hobby: ''
        }

        levelInfo.value = {
            currentLevel: 0,
            currentExp: 0,
            requiredExp: 0,
            levelName: ''
        }

        membershipInfo.value = null

        statisticsInfo.value = {
            followerCount: 0,
            followingCount: 0,
            collectionCount: 0
        }
    }

    return {
        isLoggedIn,
        userInfo,
        levelInfo,
        membershipInfo,
        statisticsInfo,
        token,
        initUserState,
        login,
        logout,
        fetchUserDetail,
        updateUserData,
        updateUserInfo, // 修正方法名
        getUserId // 导出 getUserId 方法
    }
})